<template>
  <!-- 自定义搜索 -->
  <div class="custom-form-item">
    <el-form-item :label="label" :prop="prop" :label-width="labelWidth">
      <el-autocomplete
        ref="formSearch"
        v-model="formItemKeyWord"
        readonly
        :fetch-suggestions="querySearch"
        style="width: 240px"
        placeholder="请选择"
        clearable
        class="showIcon"
        @focus="openSelect">
        <i
          slot="prefix"
          class="el-icon-search el-input__icon"
          @click="openSelect">
        </i>
        <i
          ref="clearIconRef"
          slot="suffix"
          class="el-icon-circle-close el-input__icon iconHidden"
          @click="clearKeyWord">
        </i>
      </el-autocomplete>
    </el-form-item>
    <el-dialog v-loading="loading" :title="formTitle" :visible.sync="isShow" width="1000px" center :append-to-body="true" @close="selectCancel">
      <el-row style="border-bottom: 1px solid #e5e5e5;padding-bottom: 20px;margin: 5px;">
        <el-col>
          <el-form
            ref="queryForm"
            :model="queryParams"
            size="medium"
            :inline="true"
            label-width="68px"
            style="margin: auto;width: 417px;">
            <el-form-item label="" prop="planName">
              <el-input v-model="queryParams.keyWord" placeholder="请输入关键字" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form>
          <div v-if="selectedList.length" class="checkedItem">
            <el-tooltip class="item" effect="dark" :content="selectedList[0][showField]" placement="top-start">
              <p v-if="selectedList[0].length > 10" style="padding: 5px;">
                {{ selectedList[0][showField].slice(0,10) + '...' }}
                <i class="el-icon el-icon-close" @click="tagClose()" />
              </p>
              <p v-else style="padding: 5px;">
                {{ selectedList[0][showField] }}
                <i class="el-icon el-icon-close" @click="tagClose()" />
              </p>
            </el-tooltip>
          </div>
          <vxe-table
            ref="tableRef"
            :data="tableData"
            class="mt10"
            :checkbox-config="{ checkField: 'checked', trigger: 'row' }"
            @checkbox-change="handleSelect"
            @checkbox-all="handleSelectAll">
            <vxe-column type="checkbox" width="60"></vxe-column>
            <vxe-column type="seq" :width="50" title="序号" align="center" />
            <vxe-column
              v-for="(item, index) in tableKeys"
              :key="index"
              :field="item.key"
              :title="item.title"
              :min-width="item.width"
              :sortable="item.sortable"
              show-overflow
              align="center"
            >
              <template #default="{ row }">
                <dict-tag v-if="item.dict !== undefined" :options="propDicts[item.dict]" :value="matchDicts(item.dict, row[item.key])" />
                <span v-else>
                  {{ row[item.key] }}
                </span>
              </template>
            </vxe-column>
          </vxe-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList" />
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary" @click="selectConfirm()">确 定</el-button>
        <el-button @click="selectCancel()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CustomSearch',
  props: {
    label: {
      type: String,
      default: ''
    },
    prop: {
      type: String,
      default: ''
    },
    labelWidth: {
      type: String,
      default: '100px'
    },
    tableKeys: {
      type: Array,
      default: () => []
    },
    formTitle: {
      type: String,
      default: ''
    },
    primaryKey: {
      type: String,
      default: 'id',
      required: true
    },
    showField: {
      type: String,
      default: '',
      required: true
    },
    propDicts: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      tableData: [],
      formItemKeyWord: '',
      queryParams: {
        keyWord: '',
        pageNum: 1,
        pageSize: 10,
        validFlag: '01'
      },
      multiple: false,
      loading: false,
      isShow: false,
      total: 0,
      selectedList: [],
      tempSelectedList: [],
      isEmitQuery: true
    }
  },
  watch: {
    'formItemKeyWord': {
      handler(newVal, oldVal) {
        if (this.isEmitQuery && newVal !== oldVal) {
          this.$emit('updateQueryParams', (this.selectedList[0] || [])[this.primaryKey])
        }
        this.isEmitQuery = true
      }
    }
  },
  methods: {
    setKeyWord(keyWord, primaryKey) {
      this.isEmitQuery = false
      this.formItemKeyWord = keyWord
      this.selectedList.push({[this.showField]: keyWord, [this.primaryKey]: primaryKey})
      this.tempSelectedList.push({[this.showField]: keyWord, [this.primaryKey]: primaryKey})
    },
    matchDicts(dicts, data) {
      if (data === undefined) return data
      console.log(dicts,this.propDicts);
      let dict = this.propDicts[dicts].find(i => i.value === data)
      return dict ? dict.value : data
    },
    querySearch(queryString, cb) {
      cb([])
    },
    getList() {
      this.$emit('getSearchList', this.queryParams)
    },
    // 打开选择框
    async openSelect() {
      this.loading = true
      // 触发父组件自定义事件
      await this.handleQuery()
      this.$nextTick(async() => {
        this.isShow = true
        this.loading = false
      })
    },
    // 接收父组件传过来的数据
    receive(data, total) {
      this.tableData = data || []
      this.selectedList.forEach(item => {
        let row = this.tableData.find(value => value[this.primaryKey] === item[this.primaryKey])
        this.$refs.tableRef.setCheckboxRow(row, true)
      })
      this.total = total
    },
    async handleQuery() {
      this.queryParams.pageNum = 1
      this.$emit('getSearchList', this.queryParams)
    },
    // 重置弹框对应的表单
    resetQuery() {
      this.queryParams.pageNum = 1
      this.queryParams = {
        keyWord: '',
        pageNum: 1,
        pageSize: 10
      }
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 清楚关键字查询
    clearKeyWord() {
      this.selectedList = []
      this.formItemKeyWord = ''
      this.$refs.clearIconRef.className = 'el-icon-circle-close el-input__icon iconHidden'
    },
    // 显示搜索框小图标
    showIcon() {
      this.$refs.clearIconRef.className = 'el-icon-circle-close el-input__icon iconShow'
    },
    // 单选
    handleSelect({ row, checked }) {
      this.selectedList = []
      this.tempSelectedList = [row]
      let isSelect = this.$refs.tableRef.isCheckedByCheckboxRow(row)
      this.$refs.tableRef.setAllCheckboxRow(false)
      if (checked) {
        this.selectedList.push(row)
        this.$refs.tableRef.setCheckboxRow(row, isSelect)
      }
      this.multiple = !this.selectedList.length
    },
    // 全选
    handleSelectAll({ records, checked }) {
      this.$refs.tableRef.setAllCheckboxRow(false)
      this.$modal.msgWarning('无法选择所有')
    },
    // 选择确认
    selectConfirm() {
      if (this.selectedList.length === 0) {
        return this.$modal.msgWarning(`未选择${this.label}无法进行进行确认操作!`)
      }
      this.$emit('selectDialogItem', this.selectedList[0])
      this.$nextTick(() => {
        this.showIcon()
        this.isShow = false
      })
    },
    // 选择取消
    selectCancel() {
      this.$refs.formSearch.close()
      if (!this.formItemKeyWord || this.formItemKeyWord.length === 0) {
        this.$refs.tableRef.setAllCheckboxRow(false)
        this.selectedList = []
        this.tempSelectedList = []
      } else {
        this.selectedList = this.tempSelectedList
      }
      this.isShow = false
    },
    tagClose() {
      this.selectedList = []
      this.$refs.tableRef.setAllCheckboxRow(false)
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-form-item {
  display: inline-block;
}
.showIcon :hover .iconShow{
  display: block;
}
.iconShow{
  display: none;
}
.iconHidden{
  display: none;
}
.checkedItem {
  height: 100%;
  overflow: auto;
  position: absolute;
  display: inline-block;
  top: 25px;
  z-index: 100;
}

.checkedItem > .item {
  height: 30px;
  text-align: left;
  list-style: none;
  margin: 1px auto;
  display: inline-block;
  background-color: rgba(238, 243, 247, 1);
}

.checkedItem > .item > p > i{
  margin-top:2px;
  float: right;
  cursor:pointer;
}
</style>
